import { createRouter, createWebHashHistory } from 'vue-router'
import { Local } from '@/utils/storage';

const routes = [
    {
      path: '/',
      redirect: '/home'
    },
    {
        name: 'notFound',
        path: '/:path(.*)+',
        redirect: {
            name: 'login'
        }
    },
    {
        name: 'login',
        path: '/login',
        component: () => import('@/views/login/index.vue'),
        meta: {
            title: '登录'
        }
    },
    {
        name: 'home',
        path: '/home',
        component: () => import('@/views/home/index.vue'),
        meta: {
            title: '首页'
        }
    },
    {
        name: 'person',
        path: '/person',
        component: () => import('@/views/person/index.vue'),
        meta: {
            title: '个人中心'
        }
    },
    {
        name: 'setClassHours',
        path: '/set-class-hours/:id',
        component: () => import('@/views/set-class-hours/index.vue'),
        meta: {
            title: '设置课时'
        }
    }
]

const router = createRouter({
    routes,
    history: createWebHashHistory()
})
const whiteList = ['/review'];
router.beforeEach((to, from, next) => {
    const title = to?.meta?.title
    if (title) {
        document.title = title as string
    }
    if (whiteList.includes(to.path)) {
        next();
        return;
    }
    const token = Local.get('token');
    if (to.path === '/login' && !token) {
        next();
    } else {
        if (!token) {
            next('/login');
            Local.clear();
        } else if (token && to.path === '/login') {
            next('/home');
        } else {
            next();
        }
    }
})

export default router
